package redbencity.com.richtext.richeditor;

import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.widget.EditText;


class TextColorStyle<T extends ForegroundColorSpan> extends AbstractTextStyle<T> {
    private String TAG = "TextColorStyle";

    TextColorStyle(Class<T> spanType, int type) {
        super(spanType, type);
        if (type != TextStyleFactory.FOREGROUND_COLOR_SPAN) {
            throw new IllegalArgumentException();
        }
    }

    @Override
    void cursorPositionChanged(EditText currentEditText, int start, int digits) {
        T[] typeSpans = currentEditText.getEditableText()
                .getSpans(start + digits - 1, start + digits, this.spanType);
        if (typeSpans.length > 0 && typeSpans[0] != null) {
            TextStyleFactory.textColor = typeSpans[0].getForegroundColor();
            cursorPositionChangeListener.setCursorPositionChangeListener(this.type);
            isSelect = true;
        }
    }

    @Override
    void inputTextChanged(EditText currentEditText, int start, int count) {
        T[] typeSpans = currentEditText.getEditableText().getSpans(start - 1, start, this.spanType);
        if (typeSpans.length > 0 && typeSpans[0] != null) {
            T typeSpan = typeSpans[0];
            if (typeSpan.getForegroundColor() == TextStyleFactory.textColor) {
                return;
            }
            int spanStart = currentEditText.getEditableText().getSpanStart(typeSpan);
            int spanEnd = currentEditText.getEditableText().getSpanEnd(typeSpan);
            currentEditText.getEditableText().removeSpan(typeSpan);
            currentEditText.getEditableText().setSpan(TextStyleFactory.createForegroundColorSpan(typeSpan.getForegroundColor()),
                    spanStart, start, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            currentEditText.getEditableText().setSpan(TextStyleFactory.createCharacter(this.type), start, start + count, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            if (spanEnd - start - count > 0) {
                currentEditText.getEditableText().setSpan(TextStyleFactory.createForegroundColorSpan(typeSpan.getForegroundColor()),
                        start + count, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            }
        } else {
            currentEditText.getEditableText().setSpan(TextStyleFactory.createCharacter(this.type), start, start + count, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        }
    }

}


